<template>
  <el-card>
    <el-table :data="skuList" border>
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="skuName" label="Sku名称" />
      <el-table-column prop="skuDesc" label="Sku描述" />
      <el-table-column prop="price" label="Sku价格" />
      <el-table-column prop="weight" label="Sku重量" />
      <el-table-column label="Sku默认图片">
        <template v-slot="{ row }">
          <img :src="row.skuDefaultImg" :alt="row.skuName" class="sku-img" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template v-slot="{ row }">
          <!--
            isSale
              1 售卖   已上架 -> 下架
              0 不售卖 已下架 -> 上架
           -->
          <el-button
            v-if="row.isSale"
            type="primary"
            size="small"
            @click="cancelSale(row)"
          >
            下架
          </el-button>
          <el-button v-else type="success" size="small" @click="onSale(row.id)">
            上架
          </el-button>
          <el-button v-permission="'btn.Sku.remove'" type="danger" size="small">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="prev, pager, next, jumper, total, sizes"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
</template>

<script>
export default {
  name: 'Sku',
  data() {
    return {
      skuList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },
  mounted() {
    this.getSkuList()
  },
  methods: {
    // 上架
    async onSale(skuId) {
      // 更新服务端数据
      await this.$API.product.sku.onSale(skuId)
      // 更新客户端数据 - 重新发送请求
      this.getSkuList()
    },
    // 下架
    async cancelSale(row) {
      // 更新服务端数据
      await this.$API.product.sku.cancelSale(row.id)
      // 手动更新客户端数据
      row.isSale = 0
    },
    async getSkuList() {
      const { currentPage, pageSize } = this
      const res = await this.$API.product.sku.getSkuList(currentPage, pageSize)
      this.skuList = res.data.records
      this.total = res.data.total
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.getSkuList()
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getSkuList()
    }
  }
}
</script>

<style>
.sku-img {
  width: 100px;
  height: 100px;
}
.el-pagination__sizes,
.el-pagination__total {
  float: right;
}
</style>
